package org.docmanagement.services.impl;

import java.util.List;

import org.docmanagement.commons.service.GenericServiceImpl;
import org.docmanagement.data.Category;
import org.docmanagement.services.CategoryException;
import org.docmanagement.services.CategoryService;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created on 12 oct. 2004
 * @author Mektoub
 */
@Service("categoryService")
@Transactional
public class CategoryServiceImpl extends GenericServiceImpl<Category> implements CategoryService {

	@Autowired
    public CategoryServiceImpl(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

	protected Class<Category> getObjectClass() {
		return Category.class;
	}

	public void remove(Category objectToRemove) throws CategoryException {
		Category categoryToRemove = (Category) objectToRemove;
		try {
			// Supprime la categorie parente
			DetachedCriteria criteria = DetachedCriteria.forClass(getObjectClass());
			criteria.add(Restrictions.eq("parentId", categoryToRemove.getId()));
			@SuppressWarnings("unchecked")
			List<Category> categories = getHibernateTemplate().findByCriteria(criteria);
			// On change le parent des sous-categories
			for (Category c : categories) {
				c.setParent(categoryToRemove.getParent());
				if (logger.isDebugEnabled()) {
					logger.debug("Setting parent to " + categoryToRemove.getParent() + " for category " + c);
				}
			}
			// On applique les changements en base
			getSession().flush();
			// On supprime la categorie
			super.remove(objectToRemove);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new CategoryException("Can't remove category with id: " + categoryToRemove.getId(), e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Category> findAll(Integer[] ids) throws CategoryException {
		try {
			DetachedCriteria criteria = DetachedCriteria.forClass(getObjectClass());
			criteria.add(Restrictions.in("id", ids));
			return criteria.getExecutableCriteria(getSession()).list();
		} catch (Exception e) {
			throw new CategoryException("Can't retreive categories for ids: " + ids, e);
		}
	}
}
